package org.android.kumoh_ing;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.services.GoogleKeyInitializer;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.Calendar.Events;
import com.google.api.services.calendar.model.AclRule;
import com.google.api.services.calendar.model.AclRule.Scope;
import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.CalendarList;
import com.google.api.services.calendar.model.CalendarListEntry;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.common.collect.Lists;

/**
 * Calendar Month View widget
 * 
 * @author Mike
 */
public class CalendarMonthViewActivity extends Activity {

	CalendarMonthView monthView;
	CalendarMonthAdapter monthViewAdapter;
	/** Logging level for HTTP requests/responses. */

	// ****Sample Calendar Source start
	private static final Level LOGGING_LEVEL = Level.OFF;
	private static final String TAG = "Kumoh_Ing";
	private static final String AUTH_TOKEN_TYPE = "cl";
	private static final int REQUEST_AUTHENTICATE = 0;
//	private static String resStr ="";
	final HttpTransport transport = AndroidHttp.newCompatibleTransport();
	final JsonFactory jsonFactory = new JacksonFactory();
	static final String PREF_ACCOUNT_NAME = "accountName";
	static final String PREF_AUTH_TOKEN = "authToken";
	GoogleAccountManager accountManager; 
	SharedPreferences settings;
	String accountName;  
	String authToken;
	com.google.api.services.calendar.Calendar client;
	private ArrayList<String> Event;
	private final List<CalendarListEntry> calendars = Lists.newArrayList();
	LayoutInflater inflater;
	public static final int REQUEST_CODE_ANOTHER = 1001;
	private static int position;
	private static int choicedDay;
	private static int choicedMonth;
	private String cal_id="";
	private OtherDBTransfer otherTransfer ;
	// ****Sample Calendar Source end
	Context context;
	TextView monthText;
	Button calEvent;

	int curYear;
	public int curMonth;
	String groupname;
	String group_id;
	//FileInputStream fis;
	String Info;
	String myMail;
	AlertDialog.Builder alt_bld;
	
//	String User_mail="";
	AclRule rule = new AclRule();
	Scope scope = new Scope();
	String ID = "";
	thread1 thread ;
	
	
	CalendarListView eventList;
	CalendarEventListAdapter eventAdapter;

	
	DocumentBuilderFactory factory;
	DocumentBuilder documentBuilder;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calendar);
		Event = new ArrayList<String>();
		choicedDay = java.util.Calendar.getInstance( ).get(java.util.Calendar.DAY_OF_MONTH);
		otherTransfer = new OtherDBTransfer();
	
		calEvent = (Button) findViewById(R.id.calEvent);
		groupname = getIntent().getExtras().getString("groupname");
		group_id = getIntent().getExtras().getString("group_id");
		inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		monthView = (CalendarMonthView) findViewById(R.id.monthView);
		monthText = (TextView) findViewById(R.id.monthText);
		monthViewAdapter = new CalendarMonthAdapter(this);
		alt_bld = new AlertDialog.Builder(this);
		monthView.setAdapter(monthViewAdapter);
		eventList = (CalendarListView) findViewById(R.id.caleventList);
		eventAdapter = new CalendarEventListAdapter(getApplicationContext());
		eventList.setAdapter(eventAdapter);
		myMail = Kumoh_ingActivity.My_gmail;//myMail = Information.getSharedPreference(getApplicationContext(), "My_mail");//
		thread = new thread1();

		factory = DocumentBuilderFactory.newInstance();
		try {
			documentBuilder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
		context = getApplicationContext();
		alt_bld.setTitle("일정 삭제");
		alt_bld.setIcon(R.drawable.marker);
		alt_bld.setMessage("일정을 삭제하시겠습니까??");
		alt_bld.setPositiveButton("확인", new DialogInterface.OnClickListener() {
				@Override
    			public void onClick(DialogInterface dialog, int which) {
    			// TODO Auto-generated method stub
					
    				Toast.makeText(getApplicationContext(), "확인클릭", 1000).show();
    				try{
    					CalendarEventItem tmp = (CalendarEventItem)eventAdapter.getItem(position);
					
						if(tmp.getId()==null){
							setChangedEventlist();
							tmp = (CalendarEventItem)eventAdapter.getItem(position);
						}
										
						client.events().delete(cal_id, tmp.getId()).execute();

						setChangedEventlist();
					}catch(IOException e){}
				}});
		alt_bld.setNegativeButton("취소", null);
		  
		eventList.setOnLongSelectionListener(new OnDataLongSelectionListener(){
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				position = arg2 ;
				alt_bld.show();
				return true;   
    		}
    	});
		
		setMonthText();
		calendar_auth();
		thread.start();
		//secthread.start();
		
		 monthView.setOnDataSelectionListener(new OnDataSelectionListener() {
				public void onDataSelected(AdapterView parent, View v, int position, long id) {
					MonthItem curItem = (MonthItem) monthViewAdapter.getItem(position);
					choicedDay = curItem.getDay();
					//choicedMonth = curItem.getMonth();
					setChangedEventlist();
				}
			});
		
		//calendar_check();
		
		Button monthPrevious = (Button) findViewById(R.id.monthPrevious);
		monthPrevious.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				monthViewAdapter.setPreviousMonth();
				monthViewAdapter.notifyDataSetChanged();
				//eventAdapter.notifyDataSetChanged(); 
				setMonthText();
			}
		});

		Button monthNext = (Button) findViewById(R.id.monthNext);
		monthNext.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				monthViewAdapter.setNextMonth();
				monthViewAdapter.notifyDataSetChanged();
				//eventAdapter.notifyDataSetChanged(); 
				setMonthText();
			}
		});
		
		calEvent.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),InputCalendarActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.putExtra("Month", choicedMonth);
				intent.putExtra("Day", choicedDay);
				startActivityForResult(intent, REQUEST_CODE_ANOTHER);
			}
		});
		

	}

	// ****Sample Calendar Source start
	public void calendar_auth() {
		 HttpRequestInitializer requestInitializer = new HttpRequestInitializer() {    
			 public void initialize(HttpRequest request) throws IOException { 
				 request.getHeaders().setAuthorization(GoogleHeaders.getGoogleLoginValue(authToken));   
				 }    
			 }; 
		client = new com.google.api.services.calendar.Calendar
				.Builder(transport, jsonFactory, requestInitializer)
				.setApplicationName("Kumoh_ING")
				.setJsonHttpRequestInitializer(new GoogleKeyInitializer(ClientCredentials.KEY))
				.build();
		
		settings = getPreferences(MODE_PRIVATE);
		
		accountName = settings.getString(PREF_ACCOUNT_NAME, null);
		authToken = settings.getString(PREF_AUTH_TOKEN, null);
		Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
		accountManager = new GoogleAccountManager(this);
		
		gotAccount();
				
	}

	private void setChangedEventlist(){

		int intstartYear, intstartMonth, intstartDay;
		int intendMonth, intendDay;
		Log.d("kkk", "11111");
		String id = checkHaveCalendar(calendars, groupname).getId();
		cal_id = id;
		String stringstart, stringk, stringstartday;
		String StartDate;
		String EndDate;
		String startYear;
		String startMonth;
		String startHour;
		String startMin;
		String startSec;
		String endYear;// Integer.parseInt(endformat.substring(0, 4));
		String endMonth;// Integer.parseInt(endformat.substring(5, 7));
		String endHour;
		String endMin;
		String endSec;
		Log.d("kkk", "22222");

		Events events = client.events();
		Event.clear();
		eventAdapter.clear();
		com.google.api.services.calendar.model.Events e;
		Log.d("kkk", "33333");

		try {
			e = events.list(id).execute();
			List<Event> eventlist = e.getItems();
			if(eventlist!=null){
				for (int i = 0; i < eventlist.size(); i++) {
	
					StartDate = eventlist.get(i).getStart().getDateTime().toString();
					EndDate = eventlist.get(i).getEnd().getDateTime().toString();
					startYear = StartDate.substring(0, 4);
					startMonth = StartDate.substring(5, 7);
					startHour = StartDate.substring(11, 13);
					startMin = StartDate.substring(14, 16);
					startSec = StartDate.substring(17, 19);
					endYear = EndDate.substring(0, 4);
					endMonth = EndDate.substring(5, 7);
					endHour = StartDate.substring(11, 13);
					endMin = EndDate.substring(14, 16);
					endSec = EndDate.substring(17, 19);
					intstartYear = Integer.parseInt(StartDate.substring(0, 4));
					intstartMonth = Integer.parseInt(StartDate.substring(5, 7));
					intstartDay = Integer.parseInt(StartDate.substring(8, 10));
					intendMonth = Integer.parseInt(EndDate.substring(5, 7));
					intendDay = Integer.parseInt(EndDate.substring(8, 10));
					// TODO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
					if (intstartMonth < intendMonth) {//달이 다른경우
						for (int start = intstartDay; start <= lastDay(intstartYear, intstartMonth); ++start) {
							if (start < 10) {
								stringstart = "0" + start;
							} else {
								stringstart = "" + start;
							}
							Event.add(startYear + "/" + startMonth + "/"+ stringstart + "/" + startHour + "/"+ startMin + "/" + startSec + "/"+ eventlist.get(i).getSummary());
						}
						for (int k = 1; k <= intendDay; ++k) {
							if (k < 10) {
								stringk = "0" + k;
							} else {
								stringk = "" + k;
							}
							Event.add(endYear + "/" + endMonth + "/" + stringk+ "/" + endHour + "/" + endMin + "/"+ endSec + "/"+ eventlist.get(i).getSummary());
						}
					} else if (intstartMonth == intendMonth) {//달은 같은 경우
						while (intstartDay <= intendDay) {
							if (intstartDay < 10) {
								stringstartday = "0" + intstartDay;
							} else {
								stringstartday = "" + intstartDay;
							}
							Event.add(startYear + "/" + startMonth + "/"+ stringstartday + "/" + startHour + "/"+ startMin + "/" + startSec + "/"+ eventlist.get(i).getSummary());
							intstartDay += 1;
						}
					}
					
					if(choicedDay >=Integer.parseInt(StartDate.substring(8, 10)) && choicedDay <=Integer.parseInt(EndDate.substring(8, 10)) && choicedMonth == Integer.parseInt(StartDate.substring(5, 7))){
						CalendarEventItem item = new CalendarEventItem(eventlist.get(i).getId(),StartDate,EndDate,eventlist.get(i).getSummary());	
						eventAdapter.addItem(item);
						Log.d("kkk", "44444");
					}

							
				}
				Log.d("kkk", "1");
			}
			monthViewAdapter.setEventMsg(Event);
			Log.d("kkk", "2");
			monthViewAdapter.setNextMonth();
			Log.d("kkk", "3");
			monthViewAdapter.setPreviousMonth();
			Log.d("kkk", "4");
			monthViewAdapter.notifyDataSetChanged();
			Log.d("kkk", "5");
			eventAdapter.notifyDataSetChanged();
			Log.d("kkk", "6");
			setMonthText();
			Log.d("kkk", "endendendendend");
		} catch (IOException e1) {
			Log.d("kkk", "error");

			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
	}
	

	CalendarListEntry checkHaveCalendar(List<CalendarListEntry> cal, String groupname) {
		for (int i = 0; i < cal.size(); i++) {
			if (cal.get(i).getSummary().equals(groupname))
				return cal.get(i);
		}
		return null;
	}

	void gotAccount() {
		Account account = accountManager.getAccountByName(accountName);
		
		if(account ==null){
			chooseAccount();			
			return;
		}
		if(authToken!=null){
			onAuthToken();
			return;
		}
		accountManager.getAccountManager().getAuthToken(account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>() {
					public void run(AccountManagerFuture<Bundle> future) {
						try {
							Bundle bundle = future.getResult();
							if (bundle.containsKey(AccountManager.KEY_INTENT)) {
								Log.e("Calendar Test","aaa");
								Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
								Log.e("Calendar Test","bbb");
								intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
								Log.e("Calendar Test","ccc");
								startActivityForResult(intent, REQUEST_AUTHENTICATE);
								Log.e("Calendar Test","ddd");
							} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
								setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
								//onAuthToken();//이부분에 문제가 있는게 아닌가 생각한다.!
							}
						} catch (Exception e) {
							Log.e(TAG, e.getMessage(), e);
						}
					}
				}, null);
	}

	private void chooseAccount() {
		
		AccountManagerCallback<Bundle> test = new AccountManagerCallback<Bundle>() {
			public void run(AccountManagerFuture<Bundle> future) {
				Bundle bundle;
				try {
					Toast.makeText(getApplicationContext(),"chooseAccount", 1000).show();
					bundle = future.getResult();
					setAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
					setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
					onAuthToken();
				} catch (OperationCanceledException e) {
					// user canceled
				} catch (AuthenticatorException e) {
					Log.e(TAG, "AuthenticatorException e");
					Log.e(TAG, e.getMessage(), e);
				} catch (IOException e) {
					Log.e(TAG, "IOException e");
					Log.e(TAG, e.getMessage(), e);
				}
			}
		};
		accountManager.getAccountManager().getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE, AUTH_TOKEN_TYPE, null,
				this, null, null,test , null);

	}

	void setAccountName(String accountName) {
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(PREF_ACCOUNT_NAME, accountName);
		editor.commit();
		this.accountName = accountName;
	}

	void setAuthToken(String authToken) {
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(PREF_AUTH_TOKEN, authToken);
		editor.commit();
		this.authToken = authToken;
	}

	void onAuthToken() {
		calendars.clear();
		try {
			CalendarList feed = client.calendarList().list().execute(); 
			if (feed.getItems() != null) { 
				for (CalendarListEntry calendar : feed.getItems()) {
					calendars.add(calendar);
				}
			} else {
			
			}

		} catch (IOException e) {
			handleGoogleException(e);
		}
	}

	void handleGoogleException(IOException e) {
		if (e instanceof GoogleJsonResponseException) {

			GoogleJsonResponseException exception = (GoogleJsonResponseException) e;
			// TODO(yanivi): should only try this once to avoid infinite loop
			if (exception.getStatusCode() == 401) {
				Toast.makeText(getApplicationContext(),"handleGoogleException:", 1000).show();
				accountManager.invalidateAuthToken(authToken);
				authToken = null;
				SharedPreferences.Editor editor2 = settings.edit();
				editor2.remove(PREF_AUTH_TOKEN);
				editor2.commit();
				gotAccount();
				return;
			}
		}
	}

	// ****Sample Calendar Source end

	private void setMonthText() {
		curYear = monthViewAdapter.getCurYear();
		curMonth = monthViewAdapter.getCurMonth();
		monthText.setText(curYear + "년" + (curMonth + 1) + "월");
		choicedMonth = (curMonth + 1);
	}

	public int lastDay(int yyyy, int mm) {
		int[] lastdate = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
				30, 31 };
		// 각 달의 마지막 날짜
		// var text = ""
		int year = yyyy;

		if ((0 == year % 4 && 0 != year % 100) || 0 == year % 400) { // year를
																		// 가지고
																		// 윤년인지
																		// 검사.
			lastdate[1] = 29; // 윤년인 경우 2월의 마지막 날짜를 29로 입력
		}
		int month = mm;
		int day = lastdate[month - 1];
		return day;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE_ANOTHER) {
			if (resultCode == RESULT_OK) {
				String startformat = data.getExtras().getString("startformat");
				String endformat = data.getExtras().getString("endformat");
				String summaryvalue = data.getExtras().getString("summaryvalue");
				String id = checkHaveCalendar(calendars, groupname).getId();
				cal_id = id;
				try {
					Events e = client.events();
					Event eve = new Event();
					String startYear = startformat.substring(0, 4);
					String startMonth = startformat.substring(5, 7);
					String endYear = endformat.substring(0, 4);
					String endMonth = endformat.substring(5, 7);

					DateTime starttime = DateTime.parseRfc3339(startformat/* "2012-05-09T15:00:00.000" */);
					DateTime endtime = DateTime.parseRfc3339(endformat/* "2012-05-09T15:25:00.000" */);
					eve.setStart(new EventDateTime().setDateTime(starttime));
					eve.setEnd(new EventDateTime().setDateTime(endtime));

					eve.setSummary(summaryvalue);
					e.insert(id, eve).execute();
					// TODO
					int intstartYear = Integer.parseInt(startformat.substring(0, 4));
					int intstartMonth = Integer.parseInt(startformat.substring(	5, 7));
					int intendMonth = Integer.parseInt(endformat.substring(5, 7));
					int intstartDay = Integer.parseInt(startformat.substring(8,	10));
					int intendDay = Integer.parseInt(endformat.substring(8, 10));
					String stringstart="";
					String stringi="";
					String stringstartday="";

					if (intstartMonth < intendMonth) {
						for (int start = intstartDay; start <= lastDay(intstartYear, intstartMonth); ++start) {

							if (start < 10) {
								stringstart = "0" + start;
							} else {
								stringstart = "" + start;
							}
							Event.add(startYear + "/" + startMonth + "/"
									+ stringstart + "/"
									+ startformat.substring(11, 13) + "/"
									+ "00" + "/" + "00" + "/"
									+ eve.getSummary());
							}
						for (int i = 1; i <= intendDay; ++i) {
							if (i < 10) {
								stringi = "0" + i;
							} else {
								stringi = "" + i;
							}
							Event.add(endYear + "/" + endMonth + "/" + stringi
									+ "/" + endformat.substring(11, 13) + "/"
									+ "00" + "/" + "00" + "/"
									+ eve.getSummary());
						}
					} else if (intstartMonth == intendMonth) {
						while (intstartDay <= intendDay) {
							if (intstartDay < 10) {
								stringstartday = "0" + intstartDay;
							} else {
								stringstartday = "" + intstartDay;
							}
							Event.add(startYear + "/" + startMonth + "/"
									+ stringstartday + "/"
									+ startformat.substring(11, 13) + "/"
									+ "00" + "/" + "00" + "/"
									+ eve.getSummary());
							intstartDay += 1;
						}
					}
					
										
					if(choicedDay >=Integer.parseInt(startformat.substring(8,	10)) && choicedDay <=Integer.parseInt(endformat.substring(8, 10)) && choicedMonth == Integer.parseInt(startformat.substring(5, 7))){
						CalendarEventItem item = new CalendarEventItem(eve.getId(),eve.getStart().toString().substring(10, 26),eve.getEnd().toString().substring(10, 26),eve.getSummary());	
						eventAdapter.addItem(item);
						Log.d("kkk", "44444");
					}

					//eventAdapter.addItem(item);
					eventAdapter.notifyDataSetChanged(); 
					monthViewAdapter.setEventMsg(Event);
					monthViewAdapter.setNextMonth();
					monthViewAdapter.setPreviousMonth();
					monthViewAdapter.notifyDataSetChanged();
					setMonthText();

				} catch (IOException e) {
					Toast.makeText(getApplicationContext(), "IOException e",1000).show();
				}

			} 
		}
		else if(requestCode == REQUEST_AUTHENTICATE){
			finish();
//			if (resultCode == RESULT_OK) {
//				thread.start();
//				setChangedEventlist();
//			}
		}
	}
	
	class thread1 extends Thread {
		Handler handler = new Handler();
		public void run(){
			while(accountName==null){};
			onAuthToken();
			try {
				Event.clear();
				if (checkHaveCalendar(calendars, groupname) == null ) {
					
					Log.d("cl thread", "checkHaveCalendar() 들어옴");
					Calendar entry = new Calendar();
					Calendar test;
					TimeZone zone = TimeZone.getTimeZone("GMT+09:00");
					entry.setTimeZone(zone.getDisplayName());
					entry = entry.setSummary(groupname);
					test = client.calendars().insert(entry).execute();
					calendars.clear();
					CalendarList feed = client.calendarList().list().execute();
					Log.d("cl thread", "1");
					if (feed.getItems() != null) {
						for (CalendarListEntry calendar : feed.getItems()) {
							calendars.add(calendar);
						}
					}
					//Each CalendarListEntry in this list represents a calendar
					ID = test.getId();
					String xml = otherTransfer.getGroupMemberEmail(group_id);
					scope.setType("group");
					Log.d("cl thread", "2");
					Log.d("cl thread", "xml ="+xml);
					InputStream is = new ByteArrayInputStream(xml.getBytes());
					Document doc = documentBuilder.parse(is);
					Log.d("cl thread", "3");
					Element element = doc.getDocumentElement();
					NodeList items = element.getElementsByTagName("u_gmail");
					int n = items.getLength();
					Log.d("cl thread", "4 n="+n);
					for(int i=0; i<n ; i++){
						Node item = items.item(i);
						Node text = item.getFirstChild();
						String itemValue = text.getNodeValue();
						if(itemValue.trim().equalsIgnoreCase(myMail)){
							Log.d("cl thread", "myMail="+myMail);
							continue; 
						}
						Log.d("cl thread", "itemValue="+itemValue.trim());
						scope.setValue(itemValue.trim());
						rule.setScope(scope);
						rule.setRole("owner");	
						client.acl().insert(ID, rule).execute();
						Log.d("cl thread", "enend");
					}
					
					
//					File Userinfo = getDir("Userinfo5", Activity.MODE_PRIVATE); //사용자 정보 파일 출력
					// 쓰기
//					String path = Userinfo.getAbsolutePath();
					//
//					File uInfo = new File(path + "/" + group_id + ".txt");
					
					/*
					try {
	
						fis = new FileInputStream(uInfo);
						byte[] data = new byte[fis.available()];
						while (fis.read(data) != -1) {
							;
						}// -1 전체 다읽은거
						fis.close();
	
						resStr = new String(data);// String으로 바꿔서 출력해야함. String생성자
	
					} catch (FileNotFoundException e) {
	
					} catch (IOException e) {
						// TODO Auto-generated catch block
					}*/
					
					
					//StringTokenizer res = new StringTokenizer(resStr, "//");
					
				//	while (res.hasMoreTokens()) {				
						//String curStr = res.nextToken();  //  A$B$C 형식
						//StringTokenizer _mail = new StringTokenizer(curStr, "$");
						//_mail.nextToken();
						//_mail.nextToken();
						//User_mail = _mail.nextToken();   //mail 주소 입력
					//	if(User_mail.equalsIgnoreCase(myMail)){
					//		continue;
					//	}
						
						
						
			//		}
				} else {
					Log.d("cl thread", "else");
					handler.post(new Runnable() {
						public void run() {
							setChangedEventlist();
						}
					});
					
				} 
				
			}catch (Exception ex) {
				Log.d("cl thread", "error");
			}
		}
	}	

}